//
//  LinkedListInit.swift
//  LeetCode
//
//  Created by Hao on 2020/6/21.
//  Copyright © 2020 Hao. All rights reserved.
//

import Foundation

class LinkedNode<E> {
    var element: E
    var next: LinkedNode<E>?
    init(element: E, next: LinkedNode<E>? = nil) {
        self.element = element
        self.next = next
    }
    
    static func createLinkedList<E>(array: [E]) -> LinkedNode<E>? {
        if array.count == 0 {
            return nil
        }
        var headNode = LinkedNode<E>(element: array[0], next: nil)
        let retNode = headNode
        for i in 1..<array.count {
            let curNode = LinkedNode<E>(element: array[i], next: nil)
            headNode.next = curNode
            headNode = curNode
        }
        return retNode
    }
    
    static func createSequenceList(maxRange: Int) -> LinkedNode<Int>? {
        var contents = [Int]()
        for v in 0...maxRange {
            contents.append(v)
        }
        return createLinkedList(array: contents)
    }
}

extension LinkedNode: CustomDebugStringConvertible {
    
    var debugDescription: String {
        var res = "链表内容: ["
        var firstNode: LinkedNode<E>? = self
        res.append("\(firstNode!.element)")
        firstNode = firstNode?.next
        
        while firstNode != nil {
            res.append(", \(firstNode!.element)")
            firstNode = firstNode?.next
        }
        res.append("]")
        return res
    }
    
}

/// 测试链表反转
private func testReversalList() {
    let headNode = LinkedNode<Int>.createSequenceList(maxRange: 5)
    print(headNode ?? "-")
    let newHead = ReversalList.recursive(linkedList: headNode)
    print("递归反转后链表: " + String(describing: newHead))
    print("循环反转后链表: " + String(describing: ReversalList.loop(linkedList: newHead)))
}

/// 测试合并链表
private func testMergeList() {
    let first = LinkedNode<Int>.createLinkedList(array: [1, 3, 4, 6, 8])
    let second = LinkedNode<Int>.createLinkedList(array: [0, 2, 3, 6, 9])
    let res = MergeList.twoSorted(list1: first, list2: second)
    print("合并有序列表: " + String(describing: res))
}

func _linkedListInit() {
//    testReversalList()
    
    testMergeList()
}

